/** Retrieves all traveldistances (in minutes, derived from seconds) for matrix intersections.
 *	Uses Google Maps API V3 to calculate traveldistances.
 *
 *  @author		Jos Nienhuis
 *  @since		15-08-2013
 *  @version	2.0
 * 	@copyright 	Copyright (c) 2013 Jos Nienhuis
 */

var geocoder = new google.maps.Geocoder(), distanceService = new google.maps.DistanceMatrixService();
var currentRow = 1, currentColumn = 1, amountProcessed = 0, requestDelay = 1500;
var newRow = false, progressBarWidth;

/**	Body onload, attaching eventhandlers
 *  @since		15-08-2013
 *  @version	2.3
 */
$(function(){
	$("input#process").click(function(){
		return startCalculation();
	});

	$("input#helpbtn").click(function(){
		$("div.help").slideToggle("fast");
	});

	progressBarWidth = $("div#progressbar").width();
});

/** Called by clicking the "Bereken de afstanden" button. Initiates the progressbar.
 *  @since		15-08-2013
 *  @version	1.0
 */
function startCalculation(){
	$("div#progressbar").removeClass("hidden");
	$("div#progressbar div.percentage").removeClass("hidden");
	return calculateTravelTime();
}

/** Called for each postalcode combination. Gets the locations based on the postalcode.
 *  @since		15-08-2013
 *  @version	2.2
 */
function calculateTravelTime(){
	var horizontal = $("input#horizontal" + currentColumn);
	var vertical = $("input#vertical" + currentRow);

	if(horizontal.length && vertical.length && horizontal.val() != "" && vertical.val() != ""){
		distanceService.getDistanceMatrix({
			 "origins": Array(horizontal.val()),
			 "destinations": Array(vertical.val()),
			 "travelMode": google.maps.TravelMode.DRIVING
		 	},
			function(response, status){
				if(status != google.maps.DistanceMatrixStatus.OK){
					if(console != undefined) console.log("Error: " + status);

					window.setTimeout(calculateTravelTime, requestDelay);
					return;
				}
				document.getElementById("row[" + currentRow + "][" + currentColumn + "]").value = Math.round(response.rows[0].elements[0].duration.value / 60);
				amountProcessed++;

				var percentageDone = Math.round((amountProcessed / (amount * amount)) * 100);
				var width = progressBarWidth * (percentageDone / 100);
				$("div#progressbar div.percentage").html(amountProcessed + " van " + (amount * amount) + " (" + percentageDone + "%)");
				$("div#progressbar div.done").css("width", width == 0 ? 1 : width);

				if(newRow){
					newRow = false;
					currentColumn = 0;
					currentRow++;
				}

				if(++currentColumn <= amount){
					calculateTravelTime();

					if(currentColumn == amount){
						newRow = true;
					}
				}
			});
    }
    else {
    	currentColumn = 1;
    	currentRow++;
    	calculateTravelTime();
    }

    return false;
}